package com.sc.admin.common.util;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.sc.admin.model.bo.DictBO;
import com.sc.admin.service.SysDictService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author shen chen
 * @Date 2023-08-28
 * @Description 字典工具类
 */
@Component
@Slf4j
public class DictUtils {
    private static SysDictService dictService;

    private static final String DICT_REDIS_KEY = "dict:%s";
    private static final String DICT_REDIS_LOCK_KEY = "dict-lock:";

    @Autowired
    public DictUtils(SysDictService dictService) {
        DictUtils.dictService = dictService;
    }

    /**
     * 根据类型和 value 获取 名称
     *
     * @param type  类型
     * @param value value
     * @return 名称 || ""
     */
    public static String getDictNameByValue(String type, String value) {
        List<DictBO> dictBOList = getDictByType(type);
        if (ObjectUtil.isEmpty(dictBOList)) {
            log.warn("PRO DictUtils.getDictNameByValue ObjectUtil.isEmpty(dictBOList) type:{},value:{}", type, value);
            return Constants.EMPTY;
        }

        return dictBOList.stream().filter(Objects::nonNull)
                .filter(obj -> ObjectUtil.equals(value, obj.getValue()))
                .map(DictBO::getName)
                .findFirst().orElse(Constants.EMPTY);
    }


    /**
     * 根据类型和标签获取value
     *
     * @param type         类型
     * @param label        标签
     * @param defaultValue 默认值
     * @return value || defaultValue
     */
    public static String getDictNameByValue(String type, String label, String defaultValue)  {
        String dictValue = getDictNameByValue(type, label);
        if (ObjectUtil.isEmpty(dictValue)) {
            return defaultValue;
        }
        return dictValue;
    }

    public static List<DictBO> getDictByType(String type)  {
        if (ObjectUtil.isEmpty(type)) {
            return new ArrayList<>();
        }
        String dictJson = RedisUtils.get(String.format(DICT_REDIS_KEY, type));
        if (ObjectUtil.isNotEmpty(dictJson)) {
            return JSONUtil.toList(dictJson, DictBO.class);
        }
        // 加锁,
        boolean lock = RedisUtils.tryLock(DICT_REDIS_LOCK_KEY, type, 30);
        if (!lock) {
            return new ArrayList<>();
        }
        List<DictBO> dictBOList;
        try {
            // 再查询数据库
            dictJson = RedisUtils.get(String.format(DICT_REDIS_KEY, type));
            if (ObjectUtil.isNotEmpty(dictJson)) {
                return JSONUtil.toList(dictJson, DictBO.class);
            }

            // 操作数据库
            dictBOList = dictService.getDictByType(type);
            RedisUtils.set(getFormatKey(type), JSONUtil.toJsonStr(dictBOList), 7L, TimeUnit.DAYS);
        } finally {
            // 解锁
            RedisUtils.unLock(DICT_REDIS_LOCK_KEY, type);
        }
        return dictBOList;
    }

    public static void delCache(String type) {
        RedisUtils.del(getFormatKey(type));
    }

    private static String getFormatKey(String type) {
        return String.format(DICT_REDIS_KEY, type);
    }

}
